package com.halixun.d2app.dialog;


import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.halixun.d2app.R;

import java.util.Timer;
import java.util.TimerTask;

/**
 * A simple {@link Fragment} subclass.
 */
public class PayStateDialogFragment extends DialogFragment {

    public static final String KAY_PARAMS = PayStateDialogFragment.class.getSimpleName() + "key_param";

    private TextView title;

    private ImageView image;

    private boolean payState;

    private TimerTask task;

    private Timer timer;


    public static PayStateDialogFragment getInstance(boolean payState) {
        PayStateDialogFragment f = new PayStateDialogFragment();
        Bundle params = new Bundle();
        params.putBoolean(KAY_PARAMS, payState);
        f.setArguments(params);
        return f;
    }

    public PayStateDialogFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        payState = getArguments().getBoolean(KAY_PARAMS);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_pay_state_dialog, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        setListeners(view);
        initData();
        task = new TimerTask() {
            @Override
            public void run() {
                dismiss();
            }
        };
        timer = new Timer();
        timer.schedule(task,2000);
    }

    private void initData() {
        title.setText(payState ? "支付成功" : "支付失败");
        image.setImageResource(payState?R.drawable.success:R.drawable.fail);
    }

    private void setListeners(View view) {
        view.findViewById(R.id.zhiDao).setOnClickListener(v -> dismiss());
    }

    private void initView(View view) {
        title = view.findViewById(R.id.title);
        image = view.findViewById(R.id.image);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null!=timer){
            timer.cancel();
        }
        if (null!=task){
            task.cancel();
        }
        timer = null;
        task = null;
    }
}
